/**
 * 发送模板列表页面
 */
import React from 'react';
import { Table, Form, Input, DatePicker, Button, Popconfirm, message } from 'antd';
import { history } from 'umi'
import moment from 'moment';
import { isArray, toNumber } from 'lodash';
import authHelper from '@/utils/auth/helper';
import { PageContainer, DividerContainer } from '@/molecules';
import { Pagination } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Icon } from '../components';
import { getEmailTemplateList, deleteEmailTemplate } from './service';
import styles from './index.less';

const { checkCode } = authHelper;

const templateTypeList = [
    { text: '发布/上线模板', value: '1' },
    { text: '更新模板', value: '2' },
    { text: '下线模板', value: '3' }
];

function EmailTemplate({ form, location }) {
    const { query = {} } = location;
    const { data, loading, run } = useRequest(getEmailTemplateList, {
        manual: true,
        ...defaultFormatResult
    });
    const dataSource = data?.rows || [];
    const total = data?.total || 0;

    React.useEffect(() => {
        const { orderByField = '', templateType = [], generalType = [], ...rest } = query;
        const templateTypes = isArray(templateType) ? templateType : [templateType];
        const generalTypes = isArray(generalType) ? generalType : [generalType];
        run({
            ...rest,
            templateTypes: templateTypes.map(item => toNumber(item)),
            generalTypes: generalTypes.map(item => toNumber(item)),
            orderByField: orderByField.replace('end', '')
        });
    }, [query]);

    const handleDelete = record => {
        if (record?.id) {
            deleteEmailTemplate(record.id).then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    history.push({ query: { ...query, pageNo: 1 } });
                } else {
                    message.error(msg);
                }
            });
        }
    };

    const columns = [
        {
            title: '名称',
            dataIndex: 'templateName'
        },
        {
            title: '创建人',
            dataIndex: 'createEmployeeName'
        },
        {
            title: '模板类型',
            dataIndex: 'templateType',
            filteredValue:
                query?.templateType && (isArray(query?.templateType) ? query?.templateType : [query?.templateType]),
            filters: templateTypeList,
            render: text => templateTypeList.find(item => item.value === `${text}`)?.text
        },
        {
            title: '是否通用',
            dataIndex: 'generalType',
            filteredValue:
                query?.generalType && (isArray(query?.generalType) ? query?.generalType : [query?.generalType]),
            filters: [
                { text: '是', value: '1' },
                { text: '否', value: '0' }
            ],
            render: (text, record) => (record.generalType === 1 ? '是' : '否')
        },
        {
            title: '时间',
            dataIndex: 'createTime',
            sortOrder: query.orderByField ? query.orderByField.split('|')[1] : undefined,
            sorter: () => {},
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : text)
        },
        {
            title: '操作',
            key: 'action',
            width: 100,
            className: styles.tableAction,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => (
                <DividerContainer>
                    {checkCode('office:recruitment:setting:channel:template:update') && (
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/recruitment/setting/email/template/edit',
                                    query: { id: record.id }
                                });
                            }}
                        />
                    )}
                    {checkCode('office:recruitment:setting:channel:template:delete') && (
                        <Popconfirm
                            title="确定删除该模板吗？"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => handleDelete(record)}
                        >
                            <Icon title="删除" type="listfunction_delete_icon_default" onClick={() => {}} />
                        </Popconfirm>
                    )}
                </DividerContainer>
            )
        }
    ];

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { templateType, generalType } = filters;
        const { field, order } = sorter;
        history.push({
            query: {
                ...query,
                templateType,
                generalType,
                orderByField: order ? `${field}|${order}` : '',
                pageNo: 1
            }
        });
    };

    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const { rangeTime, ...rest } = values;
                history.push({
                    query: {
                        ...query,
                        ...rest,
                        createStartDate: rangeTime?.length > 0 ? rangeTime[0].format('YYYY-MM-DD') : '',
                        createEndDate: rangeTime?.length > 1 ? rangeTime[1].format('YYYY-MM-DD') : '',
                        pageNo: 1
                    }
                });
            }
        });
    };

    return (
        <PageContainer
            title="发送模板设置"
            extra={
                <DividerContainer>
                    {
                        checkCode('office:recruitment:setting:channel:template:create') && (
                            <Button
                                type="primary"
                                onClick={() => {
                                    history.push({
                                        pathname: '/office/personnelManagement/recruitment/setting/email/template/add'
                                    });
                                }}
                            >
                                新增模板
                            </Button>
                        )
                    }
                    <Button
                        onClick={() => {
                            history.push({
                                pathname: '/office/personnelManagement/recruitment/setting/email/template/operate'
                            });
                        }}
                    >
                        操作记录
                    </Button>
                </DividerContainer>
            }
        >
            <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 16 }}>
                <Form.Item label="名称">
                    {form.getFieldDecorator('templateName', {
                        initialValue: query?.templateName || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入名称" allowClear />)}
                </Form.Item>
                <Form.Item label="创建人">
                    {form.getFieldDecorator('createEmployeeName', {
                        initialValue: query?.createEmployeeName || ''
                    })(<Input style={{ width: 148 }} placeholder="请输入创建人" allowClear />)}
                </Form.Item>
                <Form.Item label="时间">
                    {form.getFieldDecorator('rangeTime', {
                        initialValue:
                            query?.createStartDate && query?.createEndDate
                                ? [moment(query.createStartDate), moment(query.createEndDate)]
                                : undefined
                    })(<DatePicker.RangePicker style={{ width: 220 }} />)}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
            </Form>
            <Table
                rowKey="id"
                rowClassName={styles.tableRow}
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading}
                onRow={record => ({
                    onClick: () => {
                        history.push({
                            pathname: '/office/personnelManagement/recruitment/setting/email/template/detail',
                            query: { id: record.id }
                        });
                    }
                })}
            />
            <Pagination
                current={query.pageNo}
                pageSize={query.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
        </PageContainer>
    );
}

export default Form.create()(EmailTemplate);
